//
// Copyright (c) 2024 BPer
//
#include <bpersdp/BPerSSRCInfo.h>
#include <bperutil/sys/BPerLog.h>
#include <bperutil/sys/BPerCString.h>
#include <bperutil/buffer/BPerBuffer.h>

#define kCRLF  (char*)"\r\n"
bPer_vector_impl(BPerSSRCInfo)
bPer_vector_impl(BPerSSRCGroup)
bPer_vector_impl(BPersdpint)


int32_t bPer_encode_ssrcinfo(BPerSSRCInfo* info,BPerBuffer* os)
{
    int32_t err = BPer_Ok;

    if (info->ssrc == 0) {
        return bPer_error_wrap(ERROR_RTC_SDP_DECODE, "invalid ssrc");
    }
    char ssrcstr[32];
    bPer_memset(ssrcstr,0,sizeof(ssrcstr));
    bPer_itoa2(info->ssrc,ssrcstr,10);
    bPer_write_cstring(os,"a=ssrc:");
    bPer_write_cstring(os,ssrcstr);
    bPer_write_cstring(os," cname:");
    bPer_write_cstring(os,info->cname);
    bPer_write_cstring(os,kCRLF);

    if (bPer_strlen(info->msid)) {
    	 bPer_write_cstring(os,"a=ssrc:");
    	 bPer_write_cstring(os,ssrcstr);
    	 bPer_write_cstring(os, " msid:");
    	 bPer_write_cstring(os, info->msid);

        if (bPer_strlen(info->msid_tracker)) {
       	 bPer_write_cstring(os, " ");
           	 bPer_write_cstring(os, info->msid_tracker);

        }
        bPer_write_cstring(os,kCRLF);

    }
    if (bPer_strlen(info->mslabel)) {
        bPer_write_cstring(os,"a=ssrc:");
        bPer_write_cstring(os,ssrcstr);
        bPer_write_cstring(os," mslabel:");
        bPer_write_cstring(os,info->mslabel);
        bPer_write_cstring(os,kCRLF);

    }
    if (bPer_strlen(info->label)) {
        bPer_write_cstring(os,"a=ssrc:");
          bPer_write_cstring(os,ssrcstr);
          bPer_write_cstring(os," label:");
          bPer_write_cstring(os,info->label);
          bPer_write_cstring(os,kCRLF);

    }

    return err;
}

int32_t bPer_encode_ssrcgroup(BPerSSRCGroup* group,BPerBuffer* os)
{
    int32_t err = BPer_Ok;

    if (bPer_strlen(group->semantic)==0) {
        return bPer_error_wrap(ERROR_RTC_SDP_DECODE, "invalid semantics");
    }

    if (group->groups.vsize == 0) {
        return bPer_error_wrap(ERROR_RTC_SDP_DECODE, "invalid ssrcs");
    }
    bPer_write_cstring(os,"a=ssrc-group:");
    bPer_write_cstring(os,group->semantic);

    char ssrcstr[32];

    for (int32_t i = 0; i < group->groups.vsize; i++) {
    	  bPer_write_cstring(os," ");
    	     bPer_memset(ssrcstr,0,sizeof(ssrcstr));
    	     bPer_itoa(group->groups.payload[i],ssrcstr,10);
    	  bPer_write_cstring(os,ssrcstr);
      //  os << " " << m_ssrcs[i];
    }

    return err;
}

